package NWish.utils
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.SharedObject;
	import flash.net.Socket;

	public class ErrorManger
	{
		public function ErrorManger(loaderInfo)
		{
			var _uee = loaderInfo.uncaughtErrorEvents;
			_uee.addEventListener("uncaughtError", onUncaughtError);
		}
		
		private function onUncaughtError(event)
		{
			var stackTrace:String = event.error.getStackTrace();
			
			var message;
			if(event.error is Error)
			{
				message = Error(event.error).message;
			}
			else if(event.error is ErrorEvent)
			{
				message = ErrorEvent(event.error).text;
			}
			else
			{
				message = event.error.toString();
			}
			
			
			//trace('zlsg: '+message);
			trace(stackTrace);
			
			var sendError:SharedObject = SharedObject.getLocal("Errors");
			sendError.data.err = stackTrace;
		}
		
		
		static public function saveErr(str)
		{
			var sendError:SharedObject = SharedObject.getLocal("Errors");
			
			var i = 0
			while(1)
			{
				if(sendError.data['err' + i] == null)
				{
					sendError.data['err' + i] = str;
					break;
				}
				else
					++i;
			}
		}
		
		static public function sendErr(err_ip:String, __err_port:uint)
		{
			//
			var err:SharedObject = SharedObject.getLocal("Errors");
			
			if(err.data.err)
			{
				sendError(err.data.err,err_ip,__err_port);
				err.data.err = null;
			}
			
			var i = 0;
			while(1)
			{
				var n = 'err' + i;
				if(err.data[n])
				{
					sendError(err.data[n],err_ip,__err_port);
					err.data[n] = null;
				}
				else
					break;
				
				++i;
			}
			
			//test
			//sendError('test error log server!',err_ip,__err_port);
		}
		
		static private function sendError(msg,err_ip,err_port)
		{
			if(err_ip)
			{
				var socket:Socket = new Socket();
				socket.addEventListener(Event.CONNECT, cb);
				socket.addEventListener(IOErrorEvent.IO_ERROR,err);
				socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,err);
				
				
				socket.connect(err_ip, err_port);
				
				function cb()
				{
					socket.writeUTF(msg);
					socket.removeEventListener(Event.CONNECT, cb);
					//socket.close();
				}
				
				
				function err(e)
				{
					trace(e);
				}
			}
			else
				throw new Error();
		}
		
	}
}